package com.qst.controller;

import com.qst.pojo.Department;
import com.qst.pojo.Employee;
import com.qst.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * @author Eumenides.
 * @create 2021-06-20 15:35
 */
@Controller
public class RegisterController {

    @Autowired
    RegisterService service;

    /**
     * 跳转到注册页面
     *
     * @return java.lang.String
     * @Param [model]
     * @author Eumenides
     */
    @RequestMapping("/register")
    public String register(Model model) {
        List<Department> departments = service.getAllDepartments();
        model.addAttribute("departments", departments);
        return "register";
    }

    @RequestMapping("/doRegister")
    public String doRegister(Employee employee, @RequestParam("departmentID") Integer did, HttpSession session) {
        //调用service层
        String success = service.insertEmployee(employee, did);
        Employee curUser = (Employee) session.getAttribute("curUser");
        //判断是否成功注册员工
        if (success.equals("success")) { // success
            if (curUser.getRole().equals("2")) {
                return "redirect:findStatus";
            } else {
                return "redirect:/";
            }
        } else { // failed
            return "register";
        }
    }

    @RequestMapping("/registerCheck")
    public void check(Employee employee, HttpServletResponse response) throws IOException {
        int status = service.repetition(employee);
        response.setContentType("text/html;charset=utf-8");
        System.out.println("status: " + status);
        response.getWriter().append(String.valueOf( status));
    }
}
